# -*- coding: utf-8 -*-
from five import grok
from zope import schema
from plone.directives import form
from plone.indexer import indexer
from zope.interface import Invalid
from plone.app.textfield import RichText
from z3c.relationfield.schema import RelationList, RelationChoice
from plone.formwidget.contenttree import ObjPathSourceBinder,ContentTreeFieldWidget

from Products.bpContents import _

from plone.formwidget.autocomplete import AutocompleteFieldWidget
from collective.z3cform.widgets.token_input_widget import TokenInputFieldWidget
from Products.ATVocabularyManager import NamedVocabulary
from collective.gtags.field import Tags
from zope.component import getMultiAdapter
from Products.CMFCore.utils import getToolByName
from collective.z3cform.widgets.multicontent_search_widget import MultiContentSearchFieldWidget
from plone.formwidget.contenttree import MultiContentTreeFieldWidget
from Products.bpContents.adapter import KeywordSourceBinder
from plone.formwidget.autocomplete import AutocompleteMultiFieldWidget

class IArticulo(form.Schema):
    """Un artículo para el canal de Intereses de la Biblioteca Publica.
    """

    cuerpo = RichText(
        title=_(u"Cuerpo"),
        description=_(u"Texto principal"),
    )


    relaciones = RelationList(
        title=_(u"Documentos Relacionados"),
        description=_(u"Otros articulos o galerias que complementen el documento actual"),
        value_type=RelationChoice(
            source=ObjPathSourceBinder(
                   
            ),
        ),
        required=False,
    )


    form.widget(categorias=AutocompleteMultiFieldWidget)
    #categorias =schema.Choice(title=u"Categorias",source=KeywordSourceBinder())
    categorias = schema.List(title=u"Tematicas",value_type=schema.Choice(title=u"Categorias",source=KeywordSourceBinder()),required=False)

@indexer(IArticulo)
def startIndexer(context):
    if context.categorias is None:
        return None

    atvm = getToolByName(context , 'portal_vocabularies')
    engines = atvm.getVocabularyByName('categorias_vocab')
    result=[]

    for clave in context.categorias:
        result.append(clave.split(":")[0])
    return result

grok.global_adapter(startIndexer, name="articuloCategoria")

from plone.app.discussion.interfaces import IConversation
from zope.component import getMultiAdapter
from plone.memoize.instance import memoize
from Products.CMFCore.utils import getToolByName
from plone.directives.dexterity import DisplayForm
from Products.bpContents.BaseClassView import BaseClassView


class View(DisplayForm,BaseClassView):
    grok.context(IArticulo)
    grok.require('zope2.View')

    def getCategoria(self):
        """Devuelve solo el título de las categorias"""
        context=self.context
        if len(context.categorias)>0:
            r=[]

            for cate in context.categorias:
                if len(cate.split(":"))==1:
                    cate=":"+cate

                r.append(cate)
            return r
        else:
            return None

    def tieneImagenes(self):
        """Defuelve true si conteien imágenes"""

        if len(self.context.folderContext())>0:
            return True
        else:
            return False

    def parseC(self):
        from lxml import etree
        from lxml.html import fromstring, tostring
        portal_transforms=getToolByName(self.context, 'portal_transforms')
        text = self.context.cuerpo.raw
        data = portal_transforms.convertTo('text/html', text, mimetype='text/-x-web-intelligent')
        html = data.getData()
        parseado=etree.HTML(html)
        flag=0

        flag1=-1
        flag2=-1


        for element in parseado.iter("*"):

            marka=etree.Element("a")

            if element.tag=="h2":
                flag1=flag1+1
                marka.attrib['name'] = 'h-%s'%flag1
                element.addprevious(marka)
                flag2=-1
            elif element.tag=="h3":
                flag+=1
                marka.attrib['name'] = 'section-%s'%(str(flag))
                element.addprevious(marka)




        return etree.tostring(parseado)